package cn.dw.web.action;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import javax.net.ssl.SSLException;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class Faceplusplusapp {
	
	public static void main(String[] args) throws Exception{
		try {
			beauty(null);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
	
	 public static String dowloadfile(String url_) throws IOException, Throwable {
			
		    //	url_ = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=BjfUholx6_OqUA23hCqg-k9-EeavXMATKfP340I8WkNLaFFiRScOCui06C_fgJJOu5hAqVkblfq2Xt0qN3dMoh939k_j8nHU4ucrgo0N6Bsly8FWcFzly5BdN5YWQFIsRUQaACAGJF&media_id=u-xGNBS4g19Tant3g7QM4mt93fI5OfTcTWAYBACHoGRM3kR7FN_CLHdOvbEt6grq";
		    	
		    	URL url = new URL(url_);
		    	
		    	HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
		    	
		    	//防止屏蔽程序抓取而返回403错误
		        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

		     //   URI uri = new URI(url_);
		        
		        String path = "C:\\local\\";
		        
		        //得到输入流
		        InputStream inputStream = conn.getInputStream();  
		        
		        byte[]  getData = readInputStream(inputStream);
		        
		        File saveDir = new File(path);
		        
		        if(!saveDir.exists()){
		            saveDir.mkdir();
		        }
		        
		        File file = new File(path+"123.jpg");
		        
		        FileOutputStream fos = new FileOutputStream(file);
		        
		        fos.write(getData);
		        
		        if(fos!=null){
		            fos.close();  
		        }
		        if(inputStream!=null){
		            inputStream.close();
		        }
		        
				return path+"123.jpg";
		    	
			}  
	 
	 
	    public static  byte[] readInputStream(InputStream inputStream) throws IOException {  
	        byte[] buffer = new byte[1024];  
	        int len = 0;  
	        ByteArrayOutputStream bos = new ByteArrayOutputStream();  
	        while((len = inputStream.read(buffer)) != -1) {  
	            bos.write(buffer, 0, len);  
	        }  
	        bos.close();  
	        return bos.toByteArray();  
	    }  
	
	
	public static String beauty(String _url) throws IOException, Throwable {
		
		File file = new File(dowloadfile(_url));
		//dowloadfile(_url)
		byte[] buff = getBytesFromFile(file);
		String url = "https://api-cn.faceplusplus.com/facepp/v3/detect";
	    HashMap<String, String> map = new HashMap<String, String>();
	    HashMap<String, byte[]> byteMap = new HashMap<String, byte[]>();
	    map.put("api_key", "6YCJ6Y-fNu3mKY3rWNEoUMiQhMgNpk51");
	    map.put("api_secret", "xIk4aj9uaGnAviMkIPBfLnR-2xWqtjIV");
	    map.put("return_attributes", "gender,age,beauty,smiling");
	    byteMap.put("image_file", buff);
	    
	    String str = null;
	    String result = null;
	    
	    try{
	        byte[] bacd = post(url, map, byteMap);
	        str = new String(bacd);
	        
	        JSONObject jo = JSONObject.fromObject(str);
	        System.out.println(jo);
	        JSONArray faces = jo.getJSONArray("faces");
	        //jo.get("faces").toString().replace("[", "").replace("]", "")
	        
	        jo = faces.getJSONObject(0);
	        
	        jo = jo.getJSONObject("attributes").getJSONObject("beauty");
	        
	        String female_score = jo.get("female_score").toString();
	        
	        String male_score = jo.get("male_score").toString();

	        Double f_score = new Double(female_score);
	        
	        Double m_score = new Double(male_score);
	        
	        Double beauty_num = (f_score + m_score) / 2.00;
	        System.out.println(f_score+","+m_score);
	        if(beauty_num > 0 && beauty_num <= 15){
		    	result = "你的颜值低到该去重新投胎了！！！\n"
		    			+ "测试可能不准啊！！唉！唉！不要打脸啊！！！";
		    } else if (beauty_num >20 && beauty_num <= 40) {
				result = "你的颜值还是不要出来吓小朋友了！吓不到小朋友，吓坏花花草草也不好啊！！\n"
		    			+ "测试可能不准啊！！唉！唉！不要打脸啊！！！";
			} else if (beauty_num >40 && beauty_num <= 60) {
				result = "你的颜值勉强对得起观众了。。。\n"
		    			+ "测试可能不准啊！！唉！唉！不要打脸啊！！！";
			} else if (beauty_num > 60 && beauty_num <= 80) {
				result = "你的颜值好高啊，羡煞本宝宝了！！\n"
						+"测试不一定是准的，自己偷乐就行了，就不要告诉你的基友了吧！！！";
			} else if (beauty_num > 80 && beauty_num <=100) {
				result = "你的颜值可以秒杀众人，亮瞎了我的24k钛合金大眼啊！！！！啊！！！\n"
						+ "这个测试没那么准，也可能是假的！！";
			}
	        
	        System.out.println(result);
	        
	    }catch (Exception e) {
	        System.out.println(e);
		}
		return result;
	}
	
	private final static int CONNECT_TIME_OUT = 30000;
    private final static int READ_OUT_TIME = 50000;
    private static String boundaryString = getBoundary();
    @SuppressWarnings({ "rawtypes", "unchecked" })
	protected static byte[] post(String url, HashMap<String, String> map, HashMap<String, byte[]> fileMap) throws Exception {
        HttpURLConnection conne;
        URL url1 = new URL(url);
        conne = (HttpURLConnection) url1.openConnection();
        conne.setDoOutput(true);
        conne.setUseCaches(false);
        conne.setRequestMethod("POST");
        conne.setConnectTimeout(CONNECT_TIME_OUT);
        conne.setReadTimeout(READ_OUT_TIME);
        conne.setRequestProperty("accept", "*/*");
        conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
        conne.setRequestProperty("connection", "Keep-Alive");
        conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
        DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
        Iterator iter = map.entrySet().iterator();
        while(iter.hasNext()){
            Map.Entry<String, String> entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            obos.writeBytes("--" + boundaryString + "\r\n");
            obos.writeBytes("Content-Disposition: form-data; name=\"" + key
                    + "\"\r\n");
            obos.writeBytes("\r\n");
            obos.writeBytes(value + "\r\n");
        }
        if(fileMap != null && fileMap.size() > 0){
            Iterator fileIter = fileMap.entrySet().iterator();
            while(fileIter.hasNext()){
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
                obos.writeBytes("--" + boundaryString + "\r\n");
                obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
                        + "\"; filename=\"" + encode(" ") + "\"\r\n");
                obos.writeBytes("\r\n");
                obos.write(fileEntry.getValue());
                obos.writeBytes("\r\n");
            }
        }
        obos.writeBytes("--" + boundaryString + "--" + "\r\n");
        obos.writeBytes("\r\n");
        obos.flush();
        obos.close();
        InputStream ins = null;
        int code = conne.getResponseCode();
        try{
            if(code == 200){
                ins = conne.getInputStream();
            }else{
                ins = conne.getErrorStream();
            }
        }catch (SSLException e){
            e.printStackTrace();
            return new byte[0];
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len;
        while((len = ins.read(buff)) != -1){
            baos.write(buff, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        ins.close();
        return bytes;
    }
    private static String getBoundary() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i = 0; i < 32; ++i) {
            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
        }
        return sb.toString();
    }
    private static String encode(String value) throws Exception{
        return URLEncoder.encode(value, "UTF-8");
    }
    
    public static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        }
        return null;
    }
}